package org.ljy.lotterysystem.controller;


import org.ljy.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import org.ljy.lotterysystem.common.errorcode.GlobalErrorCodeConstants;
import org.ljy.lotterysystem.common.exception.ControllerException;
import org.ljy.lotterysystem.common.pojo.CommonResult;
import org.ljy.lotterysystem.common.utils.JacksonUtil;
import org.ljy.lotterysystem.controller.param.ShortMessageLoginParam;
import org.ljy.lotterysystem.controller.param.UserPasswordLoginParam;
import org.ljy.lotterysystem.controller.param.UserRegisterParam;
import org.ljy.lotterysystem.controller.result.UserBaseInfoResult;
import org.ljy.lotterysystem.controller.result.UserLoginResult;
import org.ljy.lotterysystem.controller.result.UserRegisterResult;
import org.ljy.lotterysystem.service.IUserService;
import org.ljy.lotterysystem.service.IVerificationCodeService;
import org.ljy.lotterysystem.service.dto.UserDTO;
import org.ljy.lotterysystem.service.dto.UserLoginDTO;
import org.ljy.lotterysystem.service.enums.UserIdentityEnum;
import org.ljy.lotterysystem.service.impl.UserServiceImpl;
import org.ljy.lotterysystem.service.dto.UserRegisterDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.data.redis.connection.util.DecodeUtils.convertToList;


@RestController
public class UserController {

    //日志
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    //注入Service层
//    @Autowired
//    private UserServiceImpl userService;

    @Autowired
    private IUserService userService;


    @Autowired
    private IVerificationCodeService verificationCodeService;

    /**
     * 测试接口
     *
     * @return
     */
    @RequestMapping("/test")
    public CommonResult<Integer> testController() {
        int a=10/0;
        System.out.println("异常处理");
        return CommonResult.success();
    }



    /**
     *  用户注册
     * @param param 所需参数
     * @return 返回用户id
     */
    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(
            @Validated @RequestBody UserRegisterParam param) {//把json转成对象
        System.out.println(param);
        //1.打印日志
        logger.info("userRegister param:{}", JacksonUtil.writeValueAsString(param));//把对象转成json
        //2.调用service
        UserRegisterDTO userRegisterDTO = userService.register(param);
        //3.返回结果
        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));
    }


    /**
     * 发送验证码
     * @param phoneNumber
     * @return
     */
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(String phoneNumber) {
        logger.info("sendVerificationCode phoneNumber:{}", phoneNumber);
        verificationCodeService.sendVerificationCode(phoneNumber);
        return CommonResult.success(Boolean.TRUE);
    }


    /**
     *  使用密码登录
     *
     * @param param
     * @return
     */
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userPasswordLogin(@RequestBody @Validated UserPasswordLoginParam param) {
        //1.打印日志
        logger.info("userPasswordLogin UserPasswordLoginParam:{}", JacksonUtil.writeValueAsString(param));
        //2.调用service
        UserLoginDTO userLoginDTO = userService.login(param);
        //3.封装结果并返回
        return CommonResult.success(convertToLoginResult(userLoginDTO));
    }

    /**
     * 使用验证码登陆
     * @param param
     * @return
     */
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> userMessageLogin(@RequestBody @Validated ShortMessageLoginParam param) {
        //1.打印日志
        logger.info("userMessageLogin ShortMessageLoginParam:{}", JacksonUtil.writeValueAsString(param));
        //2.调用service
        UserLoginDTO userLoginDTO = userService.login(param);
        //3.封装结果并返回
        return CommonResult.success(convertToLoginResult(userLoginDTO));
    }

    /**
     *  获取人员列表
     * @param identity
     * @return
     */
    @RequestMapping("/base-user/find-list")
    public CommonResult<List<UserBaseInfoResult>> findUserBaseInfoList(String identity) {
        logger.info("findUserBaseInfoList identity:{}", identity);
        List<UserDTO> userDTOList = userService.findUserInfo(UserIdentityEnum.forName(identity));
        return CommonResult.success(convertToList(userDTOList));
    }

    private List<UserBaseInfoResult> convertToList(List<UserDTO> userDTOList)  {
        if (CollectionUtils.isEmpty(userDTOList)) {
            return Arrays.asList();
        }

        return userDTOList.stream()
                .map(userDTO -> {
                    UserBaseInfoResult result = new UserBaseInfoResult();
                    result.setUserId(userDTO.getId());
                    result.setUserName(userDTO.getUserName());
                    result.setIdentity(userDTO.getIdentity().name());
                    return result;
                }).collect(Collectors.toList());

    }



   //   封装登陆接口返回的结果
    private UserLoginResult convertToLoginResult(UserLoginDTO userLoginDTO) {
        if(userLoginDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.RESULT_ERROR);
        }
        UserLoginResult userLoginResult = new UserLoginResult();
        userLoginResult.setToken(userLoginDTO.getToken());
        userLoginResult.setIdentity(userLoginDTO.getIdentityEnum().name());
        return userLoginResult;
    }


    //封装:用户注册返回结果data
    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO) {
        //1.校验参数
        if(userRegisterDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        //2.构造返回对象的data
        UserRegisterResult userRegisterResult = new UserRegisterResult();
        userRegisterResult.setUserId(userRegisterDTO.getUserId());
        return userRegisterResult;
    }



}
